package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.mongo.Movement;
import com.tanhua.mongo.MovementTimeLine;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 查询好友动态
     *
     * @param friendId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findFriendMovement(Long friendId, Integer page, Integer pagesize) {
        //在时间线表查询根据friendId查询数据
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, MovementTimeLine.class);
        query = query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //获取movementId集合
        List<Long> ids = CollUtil.getFieldValues(movementTimeLines, "movementId", Long.class);
        //根据movementId查询movement详情
        Criteria movementCriteria = Criteria.where("id").in(ids).and("state").is(1);
        Query movementQuery = Query.query(movementCriteria);
        List<Movement> movements = mongoTemplate.find(movementQuery, Movement.class);
        //封装数据返回
        PageResult pageResult = new PageResult(page, pagesize, count, movements);
        return pageResult;
    }

    /**
     * 发布动态
     *
     * @param movement
     */
    @Override
    public String publish(Movement movement) {
        try {
            //设置PID,""中字段不存在则创建一个新字段，有则延用
            movement.setPid(idWorker.getNextId("movement"));
            //设置当前时间
            movement.setCreated(System.currentTimeMillis());
            //movement.setId(ObjectId.get());   //可自己设置id，或者save时自动设置
            //保存当前动态
            mongoTemplate.save(movement);
            //开启Async处理（也可自建多线程处理）
            timeLineService.timeLineSave(movement.getUserId(), movement.getId());
        } catch (Exception e) {//模拟事务处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();
    }

    /**
     * 查看我的动态
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, 0L, movements);
    }

    /**
     * 随机推荐动态
     * @param counts
     * @return
     */
    @Override
    public List<Movement> randomMovement(Integer counts) {//counts为查询数目条数，这里与pageSize相同
        //第一个参数为要操作的实体类，第二个参数为数目
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //将结果设置为movement对象
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //自动将返回的数据封装为指定的movement对象
        return results.getMappedResults();
    }

    /**
     * 根据pid推荐动态
     * @param pids
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> pidMovement(List<Long> pids, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    /**
     * 根据id查询单个动态
     * @param id
     * @return
     */
    @Override
    public Movement findById(String id) {
        return mongoTemplate.findById(id,Movement.class);
    }

    /**
     * 多条件查询用户动态
     * @param uid
     * @param state
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findById(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        //构造查询条件
        if(uid != null){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null || !"".equals(state)){
            query.addCriteria(Criteria.where("state").is(state));
        }
        //查询条数
        long count = mongoTemplate.count(query, Movement.class);
        //查询动态数据
        query.skip((page - 1 )* pagesize).limit(pagesize)
            .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

    /**
     * 更新动态状态
     * @param movementId
     * @param state
     */
    @Override
    public void update(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }
}
